package Selenium.XMLReaders;

import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.ParserConfigurationException;

import org.w3c.dom.Document;
import org.w3c.dom.NodeList;
import org.w3c.dom.Node;
import org.w3c.dom.Element;
import org.xml.sax.SAXException;

import java.io.File;
import java.io.IOException;

//The main task of this class is to read the data from XML files in Config and test data folders

public class XMLClass {
	
	public String XmlFilePath;
	private DocumentBuilderFactory XMLDocumentFactory;
	private DocumentBuilder XMLDocumentBuilder;
	private File XMLFile;
	private Document Doc;
	
	
	public XMLClass(String FilePath)
	{
		XmlFilePath = FilePath;
		XMLFile = new File(FilePath);
		XMLDocumentFactory = DocumentBuilderFactory.newInstance();
		//create XML document builder
		try 
		{
			XMLDocumentBuilder = XMLDocumentFactory.newDocumentBuilder();
		} catch (ParserConfigurationException e) {
			System.out.println("Error was raised while building XML document");
		}
		
		//Trying to read XML file
		try 
		{
			Doc = XMLDocumentBuilder.parse(XMLFile);
		} catch (SAXException e) {
			System.out.println("Following SAX exception was raised: " + e.getMessage());	
		} catch (IOException e) {
			System.out.println("Following IO exception was raised: " + e.getMessage());
		}		
		Doc.getDocumentElement().normalize();	
		
	}
	
	///Read a node	
	public Node GetChildfromParent(String NodeName, String NodeIdentifier, String NodeIdentifierValue)
	{
		NodeList ChildNodes;
		Node node = null;
		ChildNodes = Doc.getElementsByTagName(NodeName);
		System.out.println("The count of the nodes is" + ChildNodes.getLength());
		Element Ele;				
		for (int i =0 ; i <= ChildNodes.getLength() - 1; i++)
		{
			Ele = (Element)ChildNodes.item(i);			
			if (Ele.getAttribute(NodeIdentifier).equals(NodeIdentifierValue))
			{
				node = Ele;
				break;
			}			
		}	
		
		return node;	
		
	}
	
	//Just to get a simple node with particular tag name
	
	
	
	
	
	//this function is used to read tag value name
	@SuppressWarnings("unused")
	private String GetTagValue(String TagName, Node Node)
	{		
		Element N = (Element)Node;
		NodeList Nlist;
		Node Targetvalue;
		Nlist = N.getElementsByTagName(TagName).item(0).getChildNodes();
		Targetvalue = Nlist.item(0);		
		return Targetvalue.getNodeValue();
		
	}
	
	//This function Returns the node list
	public NodeList GetChildNodes(Node TargetNode, String ChildTagName)
	{
		NodeList List = null;
		
		for(int i = 0; i <=TargetNode.getChildNodes().getLength() - 1; i ++)
		{
			
			
			
		}
	return List;
	}
	
	
}
